import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_class2/3681/accountRelated/account_controller.dart';
import 'package:flutter_class2/common/global.dart';
import 'package:toast/toast.dart';

class ChangeAccountPage extends StatelessWidget {
  Widget build(BuildContext context){
    return ChangeAccountPageState();
  }
}

class ChangeAccountPageState extends StatefulWidget {
  @override
  _ChangeAccountPageState createState() => new _ChangeAccountPageState();
}

class _ChangeAccountPageState extends State<ChangeAccountPageState> {

  Global global = new Global();

  bool _passwordVisibleFlag = true;// 控制密码是否为明文字符
  String newPhoneNum = '';// 获取文本框中的数值---↓
  String newEmail = '';
  String oldPassword = '';
  String newPassword = '';
  String newResetPWQuestion = '';
  String newResetPWAnswer = '';
  String newPhoneNum2 = '';// 临时存储文本框数值便于一次性存入---↓
  String newEmail2 = '';
  String newPassword2 = '';
  String newResetPWQuestion2 = '';
  String newResetPWAnswer2 = '';
  bool newPhoneNumFlag = false;// 是否更新该信息的标志位---↓
  bool newEmailFlag = false;
  bool newPasswordFlag = false;
  bool newResetPWQuestionFlag = false;
  bool newResetPWAnswerFlag = false;
  String errorToast = "";//错误信息汇总

  @override
  Widget build(BuildContext context) {
    var accountDatabaseHelper = new AccountDatabaseHelper();

    final headPic = Hero(// 创建hero动画，沟通两个组件之间的tag必须统一
      tag: 'personHeadPic',
      child: CircleAvatar(
        backgroundColor: Colors.transparent,
        radius: 48.0,
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(90)),
          child: Image.asset('images/meng.png'),
        ),
      ),
    );

    final id = Container(
      child: Text(
        Global.currentId,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: 18 ,fontWeight: FontWeight.bold),
      ),
    );

    final deleteAccount = Container(
      child: InkWell(
        child: Text(
          "注销账户?",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(color: Colors.blue,decoration: TextDecoration.underline),
        ),
        onTap: () async{
          Account account = await accountDatabaseHelper.getAccount(Global.currentId);
          var midId = account.id;
          if(oldPassword == account.password){
            accountDatabaseHelper.deleteAccount(midId);
            Toast.show('账户$midId已删除，下次登陆时生效！', context);
          }else{
            Toast.show('请在旧密码栏输入账户$midId的密码！', context);
          }
        },
      )
    );

    final phoneNum = Container(
      padding: EdgeInsets.only(top: 10),
      child: Text("手机：" + Global.currentPhoneNum),
    );

    final email = Container(
      padding: EdgeInsets.only(top: 10),
      child: Text("邮箱：" + Global.currentEmail),
    );

    final phoneNumTF = TextField(
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.number,
      inputFormatters: [
        LengthLimitingTextInputFormatter(11),
        WhitelistingTextInputFormatter(RegExp('[0-9]')),//限制输入内容为规定格式
      ],
      decoration: InputDecoration(
        hintText: '新手机（仅限中国大陆）',
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
        enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
        focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
      ),
      onChanged: (value){
        newPhoneNum = value;
      },
    );

    final emailTF = TextField(
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.emailAddress,
      inputFormatters: [
        LengthLimitingTextInputFormatter(11),
        WhitelistingTextInputFormatter(RegExp('[a-zA-Z0-9@.]')),//限制输入内容为规定格式
      ],
      decoration: InputDecoration(
        hintText: '新邮箱（记得加@××.com）',
        contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
        enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
        focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
      ),
      onChanged: (value){
        newEmail = value;
      },
    );

    final oldPasswordTF = TextField(
      autofocus: false,
      maxLines: 1,
      obscureText: _passwordVisibleFlag,
      keyboardType: TextInputType.url,
      inputFormatters: [
        LengthLimitingTextInputFormatter(12),
        WhitelistingTextInputFormatter(RegExp('[a-zA-Z0-9]')),//限制输入内容为规定格式
      ],
      decoration: InputDecoration(
          hintText: '旧密码（限6~12位字母、数字）',
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
          border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
          enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
          focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
          suffixIcon: IconButton(
            icon: Icon(_passwordVisibleFlag ? Icons.visibility : Icons.visibility_off),
            color: Colors.black54,
            onPressed: (){
              setState(() {
                _passwordVisibleFlag = !_passwordVisibleFlag;
              });
            },
          )
      ),
      onChanged: (value){
        oldPassword = value;
      },
    );

    final newPasswordTF = TextField(
      autofocus: false,
      maxLines: 1,
      obscureText: _passwordVisibleFlag,
      keyboardType: TextInputType.url,
      inputFormatters: [
        LengthLimitingTextInputFormatter(12),
        WhitelistingTextInputFormatter(RegExp('[a-zA-Z0-9]')),//限制输入内容为规定格式
      ],
      decoration: InputDecoration(
          hintText: '新密码（限6~12位字母、数字）',
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
          border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
          enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
          focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
          suffixIcon: IconButton(
            icon: Icon(_passwordVisibleFlag ? Icons.visibility : Icons.visibility_off),
            color: Colors.black54,
            onPressed: (){
              setState(() {
                _passwordVisibleFlag = !_passwordVisibleFlag;
              });
            },
          )
      ),
      onChanged: (value){
        newPassword = value;
      },
    );

    final resetPWQuestionTF = TextField(
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.url,
      inputFormatters: [
        LengthLimitingTextInputFormatter(16),
      ],
      decoration: InputDecoration(
          hintText: '新重置密码问题（限16位以下字符）',
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
        enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
        focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
      ),
      onChanged: (value){
        newResetPWQuestion = value;
      },
    );

    final resetPWAnswerTF = TextField(
      autofocus: false,
      maxLines: 1,
      keyboardType: TextInputType.url,
      inputFormatters: [
        LengthLimitingTextInputFormatter(16),
      ],
      decoration: InputDecoration(
          hintText: '新重置密码答案（限16位以下字符）',
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
        border: global.diyColorTextFieldBorder(Colors.black54),// 输入框的颜色
        enabledBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框可编辑（但未选中）时的颜色
        focusedBorder: global.diyColorTextFieldBorder(Colors.black54),// 输入框获取焦点时的颜色
      ),
      onChanged: (value){
        newResetPWAnswer = value;
      },
    );

    final saveButton = Padding(
      padding: EdgeInsets.symmetric(vertical: 16.0),
      child: RaisedButton(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        padding: EdgeInsets.all(12),
        color: Colors.black54,
        child: Text('保存', style: TextStyle(color: Colors.white)),
        onPressed: () async{
          if(newPhoneNum.length != 0){
            if(isChinaPhoneLegal(newPhoneNum)){
              newPhoneNum2 = newPhoneNum;
              newPhoneNumFlag = true;
            }else{
              errorToast = errorToast + "\n新手机不正确";
            }
          }else{
            print("新手机为空！信息不变");
          }

          if(newEmail.length != 0){
            if(isEmailLegal(newEmail)){
              newEmail2 = newEmail;
              newEmailFlag = true;
            }else{
              errorToast = errorToast + "\n新邮箱不正确";
            }
          }else{
            print("新邮箱为空！信息不变");
          }

          if(newPassword.length >=6){
            if(newPassword == oldPassword){
              newPassword2 = newPassword;
              newPasswordFlag = true;
            }else{
              errorToast = errorToast + "\n新旧密码不一致";
            }
          }else{
            print("新密码为空！信息不变");
          }

          if(newResetPWQuestion.length != 0){
            newResetPWQuestion2 = newResetPWQuestion;
            newResetPWQuestionFlag = true;
          }else{
            print("新重置问题为空！信息不变");
          }

          if(newResetPWAnswer.length != 0){
            newResetPWAnswer2 = newResetPWAnswer;
            newResetPWAnswerFlag = true;
          }else{
            print("新重置答案为空！信息不变");
          }

          if(errorToast.length > 0){// 报错信息>0，即输入内容有误
            Toast.show(errorToast+"\n", context);
            errorToast = "";
          }else{
            Account account = await accountDatabaseHelper.getAccount(Global.currentId);
            Account account2 = new Account(
                account.id,
                newPasswordFlag ? newPassword2 : account.password,
                newPhoneNumFlag ? newPhoneNum2 : account.phoneNum,
                newEmailFlag ? newEmail2 : account.email,
                account.nickName,
                account.headPic,
                account.sex,
                account.age,
                account.level,
                newResetPWQuestionFlag ? newResetPWQuestion2 : account.resetPWQuestion,
                newResetPWAnswerFlag ? newResetPWAnswer2 : account.resetPWAnswer
            );
            Global.currentPhoneNum = newPhoneNumFlag ? newPhoneNum2 : account.phoneNum;
            Global.currentEmail = newEmailFlag ? newEmail2 : account.email;
            accountDatabaseHelper.updateAccount(account2);

            Toast.show("信息修改成功，下次登陆时生效！\n请牢记您的帐户", context);
            Navigator.pop(context,true);// 传递参数true以刷新上一个页面（刷新功能暂时无效）
          }
        },
      ),
    );



    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,// 防止弹出输入法时内容溢出屏幕
      body: Center(
          child: Container(
            padding: EdgeInsets.only(left: 24.0, right: 24.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      headPic,
                      Column(
                        children: [
                          id,
                          SizedBox(height: 36,),
                          deleteAccount,
                        ],
                      ),
                    ]
                ),
                SizedBox(height: 20.0),
                Align(
                  alignment: Alignment.centerLeft,
                  child:Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      phoneNum,
                      email,
                    ],
                  ),
                ),
                SizedBox(height: 20.0),
                phoneNumTF,
                SizedBox(height: 12.0),
                emailTF,
                SizedBox(height: 36.0),
                oldPasswordTF,
                SizedBox(height: 12.0),
                newPasswordTF,
                SizedBox(height: 36.0),
                resetPWQuestionTF,
                SizedBox(height: 12.0),
                resetPWAnswerTF,
                SizedBox(height: 12.0),
                saveButton,
              ],
            ),
          )
      ),
    );
  }

  ///大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
  /// 此方法中前三位格式有： 13+任意数 * 15+除4的任意数 * 18+除1和4的任意数 * 17+除9的任意数 * 147
  bool isChinaPhoneLegal(String str) {
    return new RegExp('^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$').hasMatch(str);
  }

  /// 检查是否是邮箱格式
  bool isEmailLegal(String input) {
    if (input == null || input.isEmpty) return false;
    return new RegExp("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\$").hasMatch(input);
  }

  Future<void> successAccount(AccountDatabaseHelper db, columnId, password, phoneNum , email , resetPWQuestion , resetPWAnswer) async {
    await db.saveAccount(new Account(columnId, password, phoneNum, email, "", "", 0, 0, 0, resetPWQuestion, resetPWAnswer));
  }

}